package com.topvision.idcard;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.kernal.demo.plateid.R;
import com.topvision.commomsdk.TouchInterface;
import com.topvision.commomsdk.uitl.CameraUtil;
import com.topvision.idcard.bean.BackBean;
import com.topvision.idcard.bean.BankBean;
import com.topvision.idcard.bean.FrontBean;
import com.topvision.idcard.bean.PicBean;
import com.topvision.voicesdk.BaseVoiceActivity;
import com.topvision.voicesdk.VoiceInterface;

import java.io.File;

/**
 * Created by lucy on 2017/5/3.
 */

public class CameraActivity extends BaseVoiceActivity implements VoiceInterface, TouchInterface, ICameraActivity {
    public static final int DEFAULT_PICTURE_WIDTH = 1024;
    public static final int DEFAULT_PICTURE_HEIGHT = 768;
    public static boolean safeToTakePicture = false;
    public static final String TAKE_PHOTO_FOLDER = Environment.getExternalStorageDirectory() + File.separator + "topvisions/";
    private FrameLayout mPreview;
    private CameraView cameraView;
    private ClickCameraReceiver mClickCameraReceiver;
    //身份证前面
    private LinearLayout includeFront;
    private TextView name;
    private TextView sex;
    private TextView folk;
    private TextView birthday;
    private TextView address;
    private TextView cardno;
    //身份证后面
    private LinearLayout includeBack;
    private TextView authority;
    private TextView validdate;
    //银行卡
    private LinearLayout includeBank;
    private TextView BankName;
    private TextView CardName;
    private TextView CardNum;
    //相似度
    private LinearLayout includepic;
    private ImageView iv1;
    private ImageView iv2;
    private TextView tv;
    private TextView comparing;

    public static String TYPE;
    public static final String TYPE_MODE = "mode";
    public static final String TYPE_BANK_CAR = "bank_car";
    public static final String TYPE_ORC = "orc";
    public static boolean comparingFace = false;
    public long takePicTime = 0;
    private final int TAKE_PHOTO_TIME_VALUE = 1500;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN
                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_simplecamera);
        mPreview = (FrameLayout) findViewById(R.id.simple_preview);
        initView();
        regist();
        TYPE = getIntent().getStringExtra(TYPE_MODE);
    }

    private void initView() {
        comparing = (TextView) findViewById(R.id.comparing);
        //身份证前面
        includeFront = (LinearLayout) findViewById(R.id.includeFront);
        name = (TextView) includeFront.findViewById(R.id.name);
        sex = (TextView) includeFront.findViewById(R.id.sex);
        folk = (TextView) includeFront.findViewById(R.id.folk);
        birthday = (TextView) includeFront.findViewById(R.id.birthday);
        address = (TextView) includeFront.findViewById(R.id.address);
        cardno = (TextView) includeFront.findViewById(R.id.cardno);
        //身份证后面
        includeBack = (LinearLayout) findViewById(R.id.includeBack);
        authority = (TextView) includeBack.findViewById(R.id.authority);
        validdate = (TextView) includeBack.findViewById(R.id.validdate);
        //银行卡
        includeBank = (LinearLayout) findViewById(R.id.includeBank);
        BankName = (TextView) includeBank.findViewById(R.id.BankName);
        CardName = (TextView) includeBank.findViewById(R.id.CardName);
        CardNum = (TextView) includeBank.findViewById(R.id.CardNum);
        //相似度
        includepic = (LinearLayout) findViewById(R.id.includepic);
        iv1 = (ImageView) includepic.findViewById(R.id.iv1);
        iv2 = (ImageView) includepic.findViewById(R.id.iv2);
        tv = (TextView) includepic.findViewById(R.id.tv);
    }


    private void regist() {
        mClickCameraReceiver = new ClickCameraReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("backBean");
        filter.addAction("frontBean");
        filter.addAction("bankBean");
        filter.addAction("picBean");
        filter.addAction("comparing");
        filter.addAction("completeCompare");
        filter.addAction("com.topvision.idcard.action");
        registerReceiver(mClickCameraReceiver, filter);
    }

    private void unRegist() {
        if (mClickCameraReceiver != null) {
            unregisterReceiver(mClickCameraReceiver);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (cameraView == null) {
            initCameraView();
        }

        setVoiceInterfaceListener(this);
        setTouchInterfaceListener(this);
    }

    private void initCameraView() {
        cameraView = new CameraView(this);
        mPreview.addView(cameraView, FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT);
    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseCameraResource();
        setVoiceInterfaceListener(null);
        setTouchInterfaceListener(null);

    }


    /**
     * 释放camera资源
     *
     * @author jack
     * create at 2016/11/21 10:56
     */
    private void releaseCameraResource() {
        if (cameraView != null) {
            mPreview.removeView(cameraView);
            cameraView.freeCameraResource();
            cameraView = null;
        }
    }

    /**
     * 拍照
     *
     * @author jack
     * create at 2016/11/22 17:34
     */
    TakePhotoCallback takePhotoCallback;

    private void takePhoto() {
        long currentTime = System.currentTimeMillis();
        if (CameraActivity.safeToTakePicture && cameraView.getCameraInstance() != null && currentTime - takePicTime > TAKE_PHOTO_TIME_VALUE && !comparingFace) {
            //创建目录
            createFolder(TAKE_PHOTO_FOLDER);
            if (takePhotoCallback == null) {
                takePhotoCallback = new TakePhotoCallback(this, CameraActivity.this);
            }
            try {
                takePicTime = currentTime;
                cameraView.getCameraInstance().takePicture(null, null, takePhotoCallback);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    public static void createFolder(String folderPath) {
        File folderFile = new File(folderPath);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        takePicTime = 0;
        CameraActivity.safeToTakePicture = true;
        unRegist();
    }

    int currentZoomValue;

    @Override
    public void doForwardTouch() {
        Log.e("tvLog", "doForwardTouch");
        if (cameraView.getCameraInstance() != null) {
            //获取当前值
            Camera.Parameters parameters = cameraView.getCameraInstance().getParameters();
            currentZoomValue = parameters.getZoom();
            currentZoomValue = currentZoomValue + 5;
            CameraUtil.setZoomIn(cameraView.getCameraInstance(), currentZoomValue);

        }
    }

    @Override
    public void doBackwardTouch() {
        Log.e("tvLog", "doBackwardTouch");
        if (cameraView.getCameraInstance() != null) {
            //获取当前值
            Camera.Parameters parameters = cameraView.getCameraInstance().getParameters();
            currentZoomValue = parameters.getZoom();
            currentZoomValue = currentZoomValue - 5;
            CameraUtil.setZoomIn(cameraView.getCameraInstance(), currentZoomValue);
        }
    }

    @Override
    public void doClickTouch() {
        if (includeFront.getVisibility() == View.VISIBLE
                || includeBack.getVisibility() == View.VISIBLE
                || includeBank.getVisibility() == View.VISIBLE
                || includepic.getVisibility() == View.VISIBLE) {
            //要不要隐藏？
        } else {
            takePhoto();
        }
    }

    @Override
    public void doDoubleTouch() {

    }

    @Override
    public void dealWithVoice(String data) {
        if (data.contains("拍照")) {
            takePhoto();
        } else if (data.contains("返回")) {
            finish();
        }
        if (data.contains("放大")) {
            doForwardTouch();
        } else if (data.contains("缩小")) {
            doBackwardTouch();
        }
    }

    @Override
    public void showResultPic(byte[] people1, byte[] people2, String result) {
        //显示对比图
        showPic2(people1, people2, result);
    }


    public class ClickCameraReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            String result = intent.getStringExtra("result");
            if (action.equals("backBean")) {
                //显示身份证背面信息
                showORCback(result);
            } else if (action.equals("frontBean")) {
                //显示身份证前面信息
                showORCfront(result);
            } else if (action.equals("bankBean")) {
                //显示银行卡信息
                comparing.setVisibility(View.GONE);
                showORCbank(result);
            } else if (action.equals("com.topvision.idcard.action")) {
                //特殊处理下滑操作
                doSomething();
            } else if (action.equals("picBean")) {
                //显示对比图
                showPic(intent, result);
            } else if (action.equals("comparing")) {
                if (TYPE.equals(TYPE_ORC)) {
                    iv1.setImageAlpha(0);
                    iv2.setImageAlpha(0);
                    tv.setText("比对中...");
                    includepic.setVisibility(View.VISIBLE);
                } else if (TYPE.equals(TYPE_BANK_CAR)) {
                    comparing.setText("识别中...");
                    comparing.setVisibility(View.VISIBLE);
                }
            } else if (action.equals("completeCompare")) {
                if (TYPE.equals(TYPE_ORC)) {
                    tv.setText("识别不出结果");
                } else if (TYPE.equals(TYPE_BANK_CAR)) {
                    comparing.setText("识别不出结果");
                }
                handler.sendEmptyMessageDelayed(HIDE_VIEW, 1500);
            }
        }

        private void showPic(Intent intent, String result) {
            System.out.println("显示结果2");
            byte[] bytes1 = intent.getByteArrayExtra("bytes1");
            byte[] bytes2 = intent.getByteArrayExtra("bytes2");
            Gson gson = new Gson();
            PicBean bean = gson.fromJson(result, PicBean.class);
            //图片1
            Bitmap bitmap1 = BitmapFactory.decodeByteArray(bytes1, 0, bytes1.length);
            //图片2
            Bitmap bitmap2 = BitmapFactory.decodeByteArray(bytes2, 0, bytes2.length);
            iv1.setImageAlpha(255);
            iv2.setImageAlpha(255);
            iv1.setImageBitmap(bitmap1);
            iv2.setImageBitmap(bitmap2);
            tv.setText("相似度：" + ((int) (bean.getScore() * 100) + "%"));
        }


        private void doSomething() {
            if (includeFront.getVisibility() == View.VISIBLE
                    || includeBack.getVisibility() == View.VISIBLE
                    || includeBank.getVisibility() == View.VISIBLE
                    || includepic.getVisibility() == View.VISIBLE) {
                includeFront.setVisibility(View.GONE);
                includeBack.setVisibility(View.GONE);
                includeBank.setVisibility(View.GONE);
                includepic.setVisibility(View.GONE);
            } else {
                finish();
            }
        }

        private void showORCbank(String result) {
            Gson gson = new Gson();
            BankBean bean = gson.fromJson(result, BankBean.class);
            BankName.setText("银行名称：" + bean.getBankName());
            CardName.setText("卡别：" + bean.getCardName() + "(" + bean.getCardType() + ")");
            CardNum.setText("卡号：" + bean.getCardNum());
            includeBank.setVisibility(View.VISIBLE);
        }

        private void showORCfront(String result) {
            Gson gson = new Gson();
            FrontBean bean = gson.fromJson(result, FrontBean.class);
            name.setText("姓名：" + bean.getName());
            sex.setText("性别：" + bean.getSex());
            folk.setText("民族：" + bean.getFolk());
            birthday.setText("出生：" + bean.getBirthday());
            address.setText("地址：" + bean.getAddress());
            cardno.setText("身份证号：" + bean.getCardno());
            includeFront.setVisibility(View.VISIBLE);
        }

        private void showORCback(String result) {
            Gson gson = new Gson();
            BackBean bean = gson.fromJson(result, BackBean.class);
            authority.setText("签发机关:" + bean.getAuthority());
            validdate.setText("有效期限:" + bean.getValiddate1() + "-" + bean.getValiddate2());
            includeBack.setVisibility(View.VISIBLE);
        }
    }

    private static final int HIDE_VIEW = 1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HIDE_VIEW:
                    includepic.setVisibility(View.GONE);
                    comparing.setVisibility(View.GONE);
                    break;
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 27) {
            CameraUtil.openOrCloseLight(cameraView.getCameraInstance());
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showPic2(byte[] people1, byte[] people2, String result) {
        System.out.println("显示结果2");
        byte[] bytes1 = people1;
        byte[] bytes2 = people2;
        Gson gson = new Gson();
        final PicBean bean = gson.fromJson(result, PicBean.class);
        //图片1
        final Bitmap bitmap1 = BitmapFactory.decodeByteArray(bytes1, 0, bytes1.length);
        //图片2
        final Bitmap bitmap2 = BitmapFactory.decodeByteArray(bytes2, 0, bytes2.length);
        //显示识别结果
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                iv1.setImageAlpha(255);
                iv2.setImageAlpha(255);
                iv1.setImageBitmap(bitmap1);
                iv2.setImageBitmap(bitmap2);
                tv.setText("相似度：" + ((int) (bean.getScore() * 100) + "%"));
            }
        });

    }


}
